var express     = require('express');
var router      = express.Router();
var multer      = require('multer');
var path        = require('node:path');
var crypto      = require('node:crypto');
var password    = require(path.join(__dirname, '../utils/password'));
var database    = require(path.join(__dirname, '../utils/database'));

var uploader    = multer();

router.get('/', function(request, response) {
    // response.setHeader('Access-Control-Allow-Origin', '*');
    // console.log(request.route);
    response.json({Hello: ', World.'});
});

router.post('/login', uploader.none(), async function(req, res, next) {
    var users   = await database.query(
        "SELECT * FROM `user` WHERE `username`=?", 
        [req.body.username]
    ).then((results, fields) => {
        return results;
    });

    var logged  = false;
    if (users.length === 1) {
        logged  = await password.verify(req.body.password, users[0]['password']);
    }

    var roles   = [];
    var token   = {
        value: crypto.randomUUID(),
        expireAt: new Date(Date.now() + 7200000),
        createdAt: new Date()
    };
    if (logged) {
        await database.query(
            "INSERT INTO `user_tokens`(`user_id`, `token`, `expire_at`, `created_at`) VALUE(?, ?, ?, ?)", 
            [users[0]['id'], token.value, token.expireAt, token.createdAt]
        );

        await database.query(
            "SELECT `role`.* FROM `users_roles` " + 
            "LEFT JOIN `role` ON (`users_roles`.`role_id`=`role`.`id`) " + 
            "WHERE `users_roles`.`user_id`=?",
            [users[0]['id']]
        ).then((results, fields) => {
            roles   = results;
        });
    }

    res.json({
        id: users[0]['id'], 
        name: users[0]['name'], 
        username: users[0]['username'], 
        avatar: users[0]['avatar'], 
        createdAt: users[0]['created_at'],
        roles, 
        token: token.value,
        expireAt: token.expireAt
    });
});

router.get('/pwd', async function(req, res, next) {
    res.json(
        await password.verify(
            '123456', 
            await password.encrypt('123456')
        )
    );
});

module.exports = router;
